import router from '@/router'
import store from '@/store'
import axios from 'axios'
import { Message } from 'element-ui'
// import store from '@/store'
// import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
// 当token存在时,给每个请求加上请求头,值为token值
service.interceptors.request.use(config => {
  if (store.getters.token) {
    console.log(12342155665437)
    // 校验token是否失效
    const timeOut = 1000 * 60 * 60 * 3
    const nowTime = Date.now()
    localStorage.setItem('nowTime', nowTime)
    const loginTime = localStorage.getItem('loginTime')
    if ((nowTime - loginTime) < timeOut) {
      config.headers['Authorization'] = `Bearer ${store.getters.token}`
      // 重新写入loginTime,更新登录时间
      localStorage.setItem('loginTime', Date.now())
    } else {
      // 清空数据,跳转登录页面,阻止请求
      Message.warning('身份信息过时,请重新登录!')
      store.dispatch('user/logout')
      router.push('/login')
      return Promise.reject(new Error('身份信息过时,请重新登录!'))
    }
  }
  return config
}, err => {
  return Promise.reject(err)
})

// response interceptor
service.interceptors.response.use(res => {
  return res
}, err => {
  console.dir(err)
  const { response } = err
  if (response.data.statusCode === 400) {
    Message.warning('账号或密码错误,请重新输入!')
  }
})

export default service
